using System;
//using System.Web.Mail;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Xml;
using ASB.CC.EmailService;

namespace CCEmailService
{
    /// <summary>
    /// Summary description for EmailBySMTP.
    /// </summary>
    public class EmailBySMTP : IMailMessage
    {
        public EmailBySMTP()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region Fields

        private string _MailServer = "";
        private string _Subject = "";
        private string _Body = "";
        private string _From = "";
        private string _To = "";
        private string _CC = "";
        //		private string _BCC="";
        //		private string _Attachments="";
        private object _BodyFormat;

        #endregion

        #region Properties

        public virtual string MailServer
        {
            get { return _MailServer; }
            set { _MailServer = value; }
        }

        public virtual string Subject
        {
            get { return _Subject; }
            set { _Subject = value; }
        }

        public virtual string Body
        {
            get { return _Body; }
            set { _Body = value; }
        }

        public virtual string From
        {
            get { return _From; }
            set { _From = value; }
        }

        public virtual string To
        {
            get { return _To; }
            set { _To = value; }
        }

        public virtual string CC
        {
            get { return _CC; }
            set { _CC = value; }
        }

        public virtual object BodyFormat
        {
            get { return _BodyFormat; }
            set { _BodyFormat = value; }
        }
        #endregion

        #region Methods

        public bool Send()
        {
            try
            {
                ////MailMessage msg = new MailMessage();
                ////SmtpMail.SmtpServer = MailServer;


                ////msg.Body = Body;
                ////msg.From = From;
                ////msg.To = To;
                ////msg.Cc = CC;
                ////msg.Subject = Subject;

                ////if(BodyFormat!=null)
                ////    msg.BodyFormat=(MailFormat)BodyFormat;
                ////else
                ////    msg.BodyFormat = MailFormat.Text;
                ////Console.WriteLine("send to " + msg.To);
                ////SmtpMail.Send(msg);
                ////return true;

                //repair mail content , cover a master tempalte to the body
                //the body before must be <table><tr><td>...</td><td>...</td></tr></table>
                //we should catch the two ... first and put in the master template.

                //get master template file called Master.xml
                //string masterPath = System.Configuration.ConfigurationSettings.AppSettings["TemplatePath"].ToString() + "Master" + ".xml";
                string masterPath = Utility.GetTemplateFile("Master.xml");
                string weblinkText = System.Configuration.ConfigurationSettings.AppSettings["CCWebSiteURL"].ToString();
                if (!File.Exists(masterPath))
                {
                    //string path1 = System.Environment.CurrentDirectory + "\\asbcc_error.log";
                    //StringBuilder sb = new StringBuilder();
                    //sb.Append("Master Template not found : " + masterPath);
                    //FileStream fs = File.Open(path1, FileMode.Append, FileAccess.Write);
                    //StreamWriter sw = new StreamWriter(fs);
                    //sw.Write(sb.ToString());
                    //sw.Close();
                    //fs.Close();
                }
                else
                {
                    //get orignal content
                    XmlDocument doc = new XmlDocument();
                    try
                    {
                        string temp = Body.Replace("&", "&amp;");
                        doc.LoadXml(temp);
                    }
                    catch
                    {
                        //string path1 = System.Environment.CurrentDirectory + "\\asbcc_error.log";
                        //StringBuilder sb = new StringBuilder();
                        //sb.Append("Orignal Body is not in correct fomat : " + Body);
                        //FileStream fs = File.Open(path1, FileMode.Append, FileAccess.Write);
                        //StreamWriter sw = new StreamWriter(fs);
                        //sw.Write(sb.ToString());
                        //sw.Close();
                        //fs.Close();
                    }
                    XmlNodeList tds = doc.SelectNodes("table/tr/td");
                    string contentPlace1 = string.Empty;
                    string contentPlace2 = string.Empty;
                    if (tds.Count >= 2)
                    {
                        contentPlace1 = tds[0].InnerXml;
                        contentPlace2 = tds[1].InnerXml;
                        try
                        {
                            FileStream fs = File.OpenRead(masterPath);
                            StreamReader sr = new StreamReader(fs);
                            string masterStr = sr.ReadToEnd();
                            fs.Close();
                            sr.Close();
                            Body = masterStr.Replace("{contentPlace1}", contentPlace1).Replace("{contentPlace2}", contentPlace2).Replace("{weblink}", weblinkText);
                        }
                        catch (Exception e)
                        {
                            //string path1 = System.Environment.CurrentDirectory + "\\asbcc_error.log";
                            //StringBuilder sb = new StringBuilder();
                            //sb.Append("Error when read Master.xml : " + e.ToString());
                            //FileStream fs = File.Open(path1, FileMode.Append, FileAccess.Write);
                            //StreamWriter sw = new StreamWriter(fs);
                            //sw.Write(sb.ToString());
                            //sw.Close();
                            //fs.Close();
                        }
                    }
                }
                MailMessage msg = new MailMessage();

                msg.Body = Body;
                string configFrom = System.Configuration.ConfigurationSettings.AppSettings["SenderEmail"];
                if (!String.IsNullOrEmpty(configFrom))
                {
                    msg.From = new MailAddress(configFrom);
                }
                else if (!String.IsNullOrEmpty(From))
                {
                    msg.From = new MailAddress(From);
                }
                else
                {
                    Console.WriteLine("Format error (From): " + From);
                    return false;
                }


                if (!String.IsNullOrEmpty(To))
                {
                    foreach (string to in To.Split(';'))
                        if(!string.IsNullOrEmpty(to))
                            msg.To.Add(to);
                }
                if (!String.IsNullOrEmpty(CC))
                {
                    foreach (string cc in CC.Split(';'))
                        if (!string.IsNullOrEmpty(cc))
                            msg.CC.Add(cc);
                }
                msg.Subject = Subject;


                msg.IsBodyHtml = BodyFormat != null;
                msg.BodyEncoding = Encoding.UTF8;
                msg.SubjectEncoding = Encoding.UTF8;

                Console.WriteLine("send to " + msg.To);

                System.Net.Mail.SmtpClient sc = new SmtpClient(System.Configuration.ConfigurationSettings.AppSettings["MailServer"]);
                sc.Send(msg);

                LogEmailTracing(Body, null, null);

                //string path2 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
                //StringBuilder sb2 = new StringBuilder();
                //sb2.Append("send to " + msg.To);
                //FileStream fs2 = File.Open(path2, FileMode.Append, FileAccess.Write);	
                //StreamWriter sw2 = new StreamWriter(fs2);
                //sw2.Write(sb2.ToString());
                //sw2.Close();
                //fs2.Close();


                return true;

            }
            catch (Exception error)
            {
                string errormsg = error.ToString();
                LogEmailTracing(Body, errormsg, null);
                System.Console.WriteLine(errormsg);
                return false;
            }
            finally
            {

            }
        }

        private void LogEmailTracing(string body, string exception, string comments)
        {
            int success = 0;
            if (string.IsNullOrEmpty(exception))
                success = 1;
            using (EmailTracing dc = new EmailTracing())
            {
                EmailTraces et = new EmailTraces();
                et.From = this.From;
                et.To = this.To;
                et.CC = this.CC;
                et.BCC = null;
                et.Body = body;
                et.Exception = exception;
                et.Success = success;
                et.Comments = comments;
                dc.AddToEmailTracesSet(et);
                dc.SaveChanges();
            }

        }

        #endregion

    }
}
